package com.ask.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ask.dao.UserMongoRepository;
import com.ask.dto.UserParam;
import com.ask.model.User;

import com.ask.service.UserService;

import org.springframework.data.domain.Example;

import org.springframework.stereotype.Service;

import org.springframework.beans.factory.annotation.Autowired;

import java.util.Optional;


@Service
public class UserServiceImp implements UserService {
    private final Logger logger = LoggerFactory.getLogger(UserServiceImp.class);

    @Autowired
    private UserMongoRepository userMongoRepository;

    /**
     * 注册
     */
    @Override
    public User register(UserParam userParam){
        User user = new User();
        user.setEmail(userParam.getEmail());
        user.setHeadUrl(userParam.getHeadUrl());
        user.setNickname(userParam.getNickname());
        //查询mongo里是否有
        User aUser = userMongoRepository.findByEmail(userParam.getEmail());

        if(aUser != null){
            logger.info("注册|email已存在: "+userParam.getEmail());
            return null;
        }
        //没有就插入
        userMongoRepository.save(user);
        logger.info("注册|成功|email: "+userParam.getEmail());

        return user;
    }

    /**
     * 登录
     */
    @Override
    public User login(UserParam userParam){
        //查询mongo里是否有
        User aUser = userMongoRepository.findByEmail(userParam.getEmail());

        if(aUser != null){
            logger.info("登录|email存在: "+userParam.getEmail());
            if(userParam.getPassword()==null){
                logger.info("登录|无password|email"+userParam.getEmail());
                return null;
            }
            User returnUser = null;
            returnUser = userMongoRepository.findByPassword(userParam.getPassword());//这句取不到时不会对aUser置null
            aUser = returnUser;
            if(aUser == null){
                logger.info("登录|账号或密码不对|email: "+userParam.getEmail());
                return null;
            }
            logger.info("登录|成功|email: "+userParam.getEmail());
            return aUser;
        }
        //没有
        logger.info("登录|email未注册: "+userParam.getEmail());
        return null;
    }
}
